package org.ofbiz.autoconfig.auto;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.model.ModelField;

import com.alibaba.fastjson.JSONObject;

import javolution.util.FastList;
import javolution.util.FastMap;

public class AutoUtils {
    public static String module = AutoUtils.class.getName();
    public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");

    public static double ceil(Double num) {
	return Math.ceil(num);
    }

    public static String getObjectPath(String path) {
	if (UtilValidate.isEmpty(path)) {
	    path = "/runtime/tmp/autocode";
	}
	path = OFBIZ_HOME + path;
	return path;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List splitCustomStringToList(String inputString, String splitChar) {
	List result = FastList.newInstance();
	if (UtilValidate.isEmpty(inputString)) {
	    return result;
	}
	inputString = inputString.trim();
	String[] array = inputString.split(splitChar);
	for (int i = 0; i < array.length; i++) {
	    if (UtilValidate.isNotEmpty(array[i])) {
		result.add(array[i]);
	    }
	}
	return result;
    }

    public static Long getNowMonth(Timestamp date) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	String month = new SimpleDateFormat("MM").format(cal.getTime());
	return Long.valueOf(month);
    }

    public static Long getNowYear(Timestamp date) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	String year = new SimpleDateFormat("yyyy").format(cal.getTime());
	return Long.valueOf(year);
    }

    public static String getCurrentYear() {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
	Date date = new Date();
	return sdf.format(date);
    }

    /**
     * 获取上几天
     * 
     * @return
     */
    public static Timestamp getLastDay(Timestamp date, Long day) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	cal.add(Calendar.DATE, (int) (day * 1));
	SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	String lastMonth = dft.format(cal.getTime());
	Timestamp newTime = Timestamp.valueOf(lastMonth);
	return newTime;
    }

    public static Map<String, Object> removeOtherField(Map<String, Object> map, String entityName) {
	Delegator delegator = DelegatorFactory.getDelegator("default");
	Map<String, Object> map2 = FastMap.newInstance();
	Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
	while (it.hasNext()) {
	    Map.Entry<String, Object> entry = it.next();
	    String key = entry.getKey();
	    if (!key.equals("thisRequestUri") && !key.equals("ftlServletContext")
		    && !key.equals("_FORWARDED_FROM_SERVLET_") && !key.equals("servletContext")
		    && !key.equals("delegator") && !key.equals("_SERVER_ROOT_URL_") && !key.equals("_CONTROL_PATH_")
		    && !key.equals("security") && !key.equals("_CONTEXT_ROOT_") && !key.equals("targetRequestUri")
		    && !key.equals("_REQUEST_HANDLER_") && !key.equals("dispatcher")) {
		Object pkValue = entry.getValue();
		map2.put(key, pkValue);
	    } else {
		it.remove();
	    }
	}

	ModelEntity me = delegator.getModelEntity(entityName);

	map2 = optimizingResults(map2, me);
	return map2;
    }

    public static Map<String, Object> optimizingResults(Map<String, Object> serviceResults, ModelEntity me) {
	try {
	    Iterator<ModelField> it = me.getFieldsIterator();
	    while (it.hasNext()) {
		ModelField pkf = it.next();
		Object pkValue = serviceResults.get(pkf.getName());
		if (UtilValidate.isEmpty(pkValue)) {
		    pkValue = serviceResults.get(pkf.getName());
		    serviceResults.put(pkf.getName(), pkValue);
		}
		if (!pkf.getName().equals(pkf.getName())) {
		    serviceResults.remove(pkf.getName());
		}
		String type = pkf.getType();
		if (UtilValidate.isNotEmpty(pkValue)) {
		    if (type.equals("date-time")) {
			if (!isValidDate(String.valueOf(pkValue))) {
			    pkValue = pkValue + " 00:00:00";
			}
			serviceResults.put(pkf.getName(), Timestamp.valueOf(String.valueOf(pkValue)));
		    } else if (type.equals("date") || type.equals("Date")) {
			serviceResults.put(pkf.getName(),
				java.sql.Date.valueOf(String.valueOf(serviceResults.get(pkf.getName()))));
		    } else if (type.equals("time")) {
			serviceResults.put(pkf.getName(),
				java.sql.Time.valueOf(String.valueOf(serviceResults.get(pkf.getName()))));
		    } else if (type.equals("currency-amount") || type.equals("currency-precise")
			    || type.equals("fixed-point")) {
			serviceResults.put(pkf.getName(),
				BigDecimal.valueOf(Double.valueOf(String.valueOf(serviceResults.get(pkf.getName())))));
		    } else if (type.equals("floating-point")) {
			serviceResults.put(pkf.getName(),
				Double.valueOf(String.valueOf(serviceResults.get(pkf.getName()))));
		    } else if (type.equals("numeric")) {
			serviceResults.put(pkf.getName(),
				Long.valueOf(String.valueOf(serviceResults.get(pkf.getName()))));
		    } else if (type.equals("byte-array")) {
			byte[] o = String.valueOf(serviceResults.get(pkf.getName())).getBytes();
			serviceResults.put(pkf.getName(), o);
		    } else {
			serviceResults.put(pkf.getName(), String.valueOf(serviceResults.get(pkf.getName())));
		    }
		}
	    }
	} catch (NumberFormatException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return serviceResults;
    }

    public static String optimizingType(String entityName, String fieldName) {
	Delegator delegator = DelegatorFactory.getDelegator("default");
	ModelEntity me = delegator.getModelEntity(entityName);
	String type = me.getField(fieldName).getType();
	return type;
    }
    
    public static void main(String[] args) {
    	// TODO Auto-generated method stub
String ss="typeId=EMPLOYEE&workState!=2";

Map mm =upperCond(ss);
System.out.println(mm);

        }

    public static Map<String, Object> upperCond(String condition) {
	Map<String, Object> condMap = FastMap.newInstance();
	String[] conds = condition.split("&");
		for (int i = 0; i < conds.length; i++) {
			String condInfo =conds[i].trim();
			if(condInfo.contains("!=")) {
				String[] condInfos = condInfo.split("!=");
			    String key = condInfos[0].trim();
			    String value = condInfos[1].trim().replaceAll("'", "");
			    condMap.put(key, value);
			    condMap.put(key+"_op", "notEqual");
			    
			}else {
				String[] condInfos = condInfo.split("=");
			    String key = condInfos[0].trim();
			    String value = condInfos[1].trim().replaceAll("'", "");
			    condMap.put(key, value);
			}
			
			
		    
		}
	return condMap;
    }

    public static Map<String, Object> dictToMap(String dictTable) {
	Map<String, Object> resultMap = new HashMap<>();
	JSONObject jasonObject = JSONObject.parseObject(dictTable);
	resultMap = (Map<String, Object>) jasonObject;
	String condition = jasonObject.getString("condition");
	Map<String, Object> condMap = FastMap.newInstance();
	String[] conds = condition.split("&");
	for (int i = 0; i < conds.length; i++) {
	    String[] condInfos = conds[i].trim().split("=");
	    String key = condInfos[0].trim();
	    String value = condInfos[1].trim().replaceAll("'", "");
	    condMap.put(key, value);
	}
	resultMap.put("newCondition", condMap);
	resultMap.put("oldCondition", resultMap.get("condition"));
	resultMap.remove("condition");

	Iterator<Map.Entry<String, Object>> it = resultMap.entrySet().iterator();
	while (it.hasNext()) {
	    Map.Entry<String, Object> entry = it.next();
	    String key = entry.getKey();
	    if (!key.equals("newCondition") && !key.equals("oldCondition")) {
		String pkValue = (String) entry.getValue();
		resultMap.put(key, pkValue);
	    }
	}
	return resultMap;
    }

    public static Map<String, Object> dictToMapFree(String dictTable) {
	Map<String, Object> resultMap = new HashMap<>();
	JSONObject jasonObject = JSONObject.parseObject(dictTable);
	resultMap = (Map<String, Object>) jasonObject;
	Iterator<Map.Entry<String, Object>> it = resultMap.entrySet().iterator();
	while (it.hasNext()) {
	    Map.Entry<String, Object> entry = it.next();
	    String key = entry.getKey();
	    String pkValue = (String) entry.getValue();
	    resultMap.put(key, pkValue);
	}
	return resultMap;
    }

    public static boolean isValidDate(String str) {
	boolean convertSuccess = true;
	// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
	    format.setLenient(false);
	    format.parse(str);
	} catch (ParseException e) {
	    convertSuccess = false;
	}
	return convertSuccess;
    }

}